package com.nit.store.controller;

import com.nit.store.pojo.dto.output.AddressDto;
import com.nit.store.service.AddressService;
import com.nit.store.util.JwtUtils;
import com.nit.store.web.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Author J1ay
 * @Date 2022/7/21 18:56
 * @Description 地址管理
 */
@RestController
@RequestMapping("/addresses")
@Slf4j
public class AddressController {

    @Value("${jwt.tokenHeader}")
    private String tokenHeader;

    @Autowired
    AddressService addressService;

    @Autowired
    private JwtUtils jwtUtils;

    /**
     * 展示地址
     * @return
     */
    @PreAuthorize("hasAuthority('/address/show')")
    @GetMapping("/")
    public JsonResult<List<AddressDto>> getAddress(@RequestHeader(value="Authentication")String token) {
        Long uid = jwtUtils.parseJwtGetId(token.substring(tokenHeader.length()));
        return JsonResult.ok(addressService.getAddress(uid));
    }

    /**
     * 更新地址
     * @param aid
     */
    @PreAuthorize("hasAuthority('/address/update')")
    @PostMapping("/{aid}/set_default")
    public JsonResult<Void> setDefault(@PathVariable("aid") Long aid, @RequestHeader(value="Authentication")String token) {
        Long uid = jwtUtils.parseJwtGetId(token.substring(tokenHeader.length()));
        addressService.setDefault(aid, uid);
        return JsonResult.ok();
    }

    @PreAuthorize("hasAuthority('/address/delete')")
    @PostMapping("/{aid}/delete")
    public JsonResult<Void> delete(@PathVariable("aid") Long aid) {
        addressService.delete(aid);
        return JsonResult.ok();
    }


    @PreAuthorize("hasAuthority('/address/add')")
    @PostMapping("/addnew")
    public JsonResult<Void> addNew(String receiver,
                       String provinceCode,
                       String cityCode,
                       String areaCode,
                       String zip,
                       String address,
                       String phone,
                       String tel,
                       String tag, @RequestHeader(value="Authentication") String token) {
        Long uid = jwtUtils.parseJwtGetId(token.substring(tokenHeader.length()));
        String username = jwtUtils.parseJwtGetName(token.substring(tokenHeader.length()));
        System.out.println("username====>" + username);
        System.out.println("uid====>" + uid);
        addressService.add(receiver, provinceCode, cityCode, areaCode, zip, address, phone, tel, tag, username, uid);
        return JsonResult.ok();
    }
}
